package com.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.test.core.MainService;
import com.test.objects.Author;

@SuppressWarnings("serial")
public class MainServlet extends HttpServlet {
	static String MAIN_SERVICE_BEAN = "mainServiceBean";
	MainService mainService;
	
	@Override
	public void init() throws ServletException {
		WebApplicationContext context = WebApplicationContextUtils.
				getWebApplicationContext(getServletContext());
		mainService = (MainService)context.getBean(MAIN_SERVICE_BEAN);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/xml");
		PrintWriter out = res.getWriter();
		
		String request = req.getParameter("req");
		
		HttpSession currSession = req.getSession();
		Author author = (Author)currSession.getAttribute("author");
		
		if (author == null){
			out.println(this.mainService.getAuthorError());
			out.flush();
			return;
		}
		
		if (request.equals("mrcs")){
			int ownerId = author.getId();
			String aId = req.getParameter("aId");
			int offset = Integer.parseInt(req.getParameter("offs"));
			int authorId = (aId != null && Integer.parseInt(aId) != 0) ?
					Integer.parseInt(aId) : ownerId;
			String mostRecentCmts = this.mainService.
					getMostRecentCommentsInHtml(ownerId, authorId, offset);
			out.println(mostRecentCmts);
		}else if (request.equals("add")){
			String data = req.getParameter("data");
			String retStr = this.mainService.saveComment(data);
			out.println(retStr);
		}else if (request.equals("madd")){
			String data = req.getParameter("data");
			String retStr = this.mainService.saveMainComment(data);
			out.println(retStr);
		}else if (request.equals("rel")){
			int ownerId = author.getId();
			String aId = req.getParameter("aId");
			int authorId = (aId != null && Integer.parseInt(aId) != 0) ?
					Integer.parseInt(aId) : ownerId;
			String relation = this.mainService.getLimitRelation(authorId);
			out.println(relation);
		}else if (request.equals("del")){
			int cmtId = Integer.parseInt(req.getParameter("id"));
			out.println(this.mainService.removeComment(cmtId));
		}
		
		out.flush();
	}
	
	
}
